﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PrVyd;
using System.Xml;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using PrVyd.Zakladni_tridy;

namespace PrVyd.Dialogova_okna
{
    public partial class WFaktura : Form
    {
        private XmlDocument doc;
        private XmlElement invoice;
        public String[] DatagridInfo;

        public WFaktura(XmlDocument doc)
        {
            InitializeComponent();

            this.doc = doc;
            DatagridInfo = new String[4];

            this.txtDDic.Text = Zakladni_tridy.ConfigManager.DIC;
            this.txtDIc.Text = Zakladni_tridy.ConfigManager.ICO;
            this.txtDMesto.Text = Zakladni_tridy.ConfigManager.City;
            this.txtDPsc.Text = Zakladni_tridy.ConfigManager.Zip;
            this.txtDUlice.Text = Zakladni_tridy.ConfigManager.Street;
            this.txtDodavatel.Text = Zakladni_tridy.ConfigManager.Name + " " + Zakladni_tridy.ConfigManager.Surname;
            
        }
        public WFaktura(XmlDocument doc, XmlElement invoice)
        {
            InitializeComponent();

            this.doc = doc;
            this.invoice = invoice;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.addItem();
        }

        public void delete_Click(object sender, EventArgs e)
        {
            ((sender as Button).Parent.Parent as Panel).Controls.Remove((sender as Button).Parent);
        }

        public void prepocet(object sender, EventArgs e)
        {
            double price = 0;

            foreach(Panel p in pItems.Controls){
                NumericUpDown count, dph;
                count = p.Controls[2] as NumericUpDown;
                dph = p.Controls[4] as NumericUpDown;

                String cena = "0";
                if ((p.Controls[3] as TextBox).Text.Length > 0)
                    cena = (p.Controls[3] as TextBox).Text;

                price+= Convert.ToDouble(count.Value) * Convert.ToDouble(cena) * (100.0 + Convert.ToDouble(dph.Value)) / 100.0;
            }

            lblTotal.Text = Convert.ToString(price) + " Kč";
            lbltoPay.Text = Convert.ToString(price) + " Kč";
        }

        public void prepocet_radek(object sender, EventArgs e)
        {
            double price = 0;

            Panel p = (sender as Control).Parent as Panel;
            NumericUpDown count, dph;
            count = p.Controls[2] as NumericUpDown;
            dph = p.Controls[4] as NumericUpDown;

            String cena = "0";
            if ((p.Controls[3] as TextBox).Text.Length > 0)
                cena = (p.Controls[3] as TextBox).Text;

            price = Convert.ToDouble(count.Value) * Convert.ToDouble(cena) * (100.0 + Convert.ToDouble(dph.Value)) * 0.01;

            (p.Controls[5] as Label).Text = Convert.ToString(price) + " Kč";
        }

        private Panel addItem()
        {
            TextBox desc = new TextBox();
            NumericUpDown count = new NumericUpDown();
            count.Size = new System.Drawing.Size(38, 21);
            count.ValueChanged += new EventHandler(prepocet);
            count.ValueChanged += new EventHandler(prepocet_radek);

            TextBox price = new TextBox();
            price.Size = new System.Drawing.Size(66, 21);
            price.TextChanged += new EventHandler(prepocet);
            price.TextChanged += new EventHandler(prepocet_radek);

            NumericUpDown dph = new NumericUpDown();
            dph.Size = new System.Drawing.Size(34, 21);
            dph.ValueChanged += new EventHandler(prepocet);
            dph.ValueChanged += new EventHandler(prepocet_radek);

            Label total = new Label();
            total.Size = new System.Drawing.Size(87, 21);
            total.Text = "0,00 Kč";
            total.TextAlign = ContentAlignment.MiddleRight;

            Button delete = new Button();
            delete.Dock = DockStyle.Left;
            delete.Text = "-";
            delete.Size = new System.Drawing.Size(30, 21);
            delete.Font = new System.Drawing.Font("Calibri", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
            delete.UseVisualStyleBackColor = true;
            delete.Click += new EventHandler(delete_Click);
            delete.Click += new EventHandler(prepocet);


            desc.Dock = DockStyle.Fill;
            count.Dock = DockStyle.Right;
            price.Dock = DockStyle.Right;
            dph.Dock = DockStyle.Right;
            total.Dock = DockStyle.Right;


            Panel panel = new Panel();
            panel.Padding = new System.Windows.Forms.Padding(0, 2, 0, 2);
            panel.Size = new System.Drawing.Size(120, 25);
            panel.Dock = DockStyle.Bottom;
            panel.Controls.Add(desc);
            panel.Controls.Add(delete);
            panel.Controls.Add(count);
            panel.Controls.Add(price);
            panel.Controls.Add(dph);
            panel.Controls.Add(total);


            this.pItems.Controls.Add(panel);

            return panel;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if (txtOdberatel.Text.Length == 0)
            {
                MessageBox.Show("Odběratel musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtOUlice.Text.Length == 0)
            {
                MessageBox.Show("Ulice odběratele musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtOMesto.Text.Length == 0)
            {
                MessageBox.Show("Město odběratele musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtOPsc.Text.Length == 0)
            {
                MessageBox.Show("PSČ odběratele musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!Regex.IsMatch(txtOPsc.Text, @"^[0-9]{5}$"))
            {
                MessageBox.Show("PSČ odběratele musí být v platném tvaru (12345)", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtOIc.Text.Length > 0 && !Regex.IsMatch(txtOIc.Text, @"^[A-Z]{0,2}[0-9]+$"))
            {
                MessageBox.Show("Ič odběratele musí být v platném tvaru", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtODic.Text.Length > 0 && !Regex.IsMatch(txtODic.Text, @"^([A-Z]{2}[0-9]+)?$"))
            {
                MessageBox.Show("Dič odběratele musí být v platném tvaru", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (txtDodavatel.Text.Length == 0)
            {
                MessageBox.Show("Dodavatel musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtDUlice.Text.Length == 0)
            {
                MessageBox.Show("Ulice dodavatele musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtDMesto.Text.Length == 0)
            {
                MessageBox.Show("Město dodavatele musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtDPsc.Text.Length == 0)
            {
                MessageBox.Show("PSČ dodavatele musí být vyplněn", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!Regex.IsMatch(txtDPsc.Text, @"^[0-9]{5}$"))
            {
                MessageBox.Show("PSČ dodavatele musí být v platném tvaru (12345)", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!Regex.IsMatch(txtDIc.Text, @"^[A-Z]{0,2}[0-9]+$"))
            {
                MessageBox.Show("Ič dodavatele musí být v platném tvaru", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtDDic.Text.Length > 0 && !Regex.IsMatch(txtDDic.Text, @"^([A-Z]{2}[0-9]+)?$"))
            {
                MessageBox.Show("Dič dodavatele musí být v platném tvaru", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.pItems.Controls.Count == 0)
            {
                MessageBox.Show("Faktura nemá žádné položky", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (numNumber.Enabled)
            {
                if ((from x in DatabaseManager.LoadDBX().Descendants("invoice")
                     where x.Attribute("number").Value.Equals(numNumber.Value.ToString())
                     select x).Count() > 0)
                {
                    MessageBox.Show("Faktura s daným číslem již existuje.", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (this.invoice == null)
                this.doInvoice();

            invoice["items"].RemoveAll();
            foreach (Panel p in this.pItems.Controls)
            {
                XmlElement item = doc.CreateElement("item");
                invoice["items"].AppendChild(item);

                XmlElement desc = doc.CreateElement("description");
                desc.InnerText = (p.Controls[0] as TextBox).Text;
                item.AppendChild(desc);

                XmlElement count = doc.CreateElement("count");
                count.InnerText = (p.Controls[2] as NumericUpDown).Value.ToString();
                item.AppendChild(count);

                XmlElement price = doc.CreateElement("price");
                price.InnerText = (p.Controls[3] as TextBox).Text;
                item.AppendChild(price);

                XmlElement vat = doc.CreateElement("vat");
                vat.InnerText = (p.Controls[4] as NumericUpDown).Value.ToString();
                item.AppendChild(vat);
            }

            invoice.SetAttribute("number", numNumber.Value.ToString());

            invoice["due"].InnerText = dateSplatnost.Value.ToString("yyyy-MM-dd");
            invoice["created"].InnerText = dateVystaveno.Value.ToString("yyyy-MM-dd");
            invoice["customer"]["firm"].InnerText = txtOdberatel.Text.Trim();
            invoice["customer"]["street"].InnerText = txtOUlice.Text.Trim();
            invoice["customer"]["city"].InnerText = txtOMesto.Text.Trim();
            invoice["customer"]["zip"].InnerText = txtOPsc.Text.Trim();
            if (txtOIc.Text.Length > 0)
                invoice["customer"]["ic"].InnerText = txtOIc.Text;
            if (txtODic.Text.Length > 0)
                invoice["customer"]["dic"].InnerText = txtODic.Text.Trim();

            invoice["supplier"]["firm"].InnerText = txtDodavatel.Text.Trim();
            invoice["supplier"]["street"].InnerText = txtDUlice.Text.Trim();
            invoice["supplier"]["city"].InnerText = txtDMesto.Text.Trim();
            invoice["supplier"]["zip"].InnerText = txtDPsc.Text.Trim();
            invoice["supplier"]["ic"].InnerText = txtDIc.Text.Trim();
            if (txtDDic.Text.Length > 0)
                invoice["supplier"]["dic"].InnerText = txtDDic.Text.Trim();

            DatagridInfo[0] = numNumber.Value.ToString();
            DatagridInfo[1] = txtOdberatel.Text;
            DatagridInfo[2] = lbltoPay.Text;
            DatagridInfo[3] = dateSplatnost.Value.ToShortDateString();
            

            this.DialogResult = DialogResult.OK;
        }

        private void doInvoice()
        {
            invoice = doc.CreateElement("invoice");
            doc.SelectNodes("/database/invoices")[0].AppendChild(invoice);

            invoice.AppendChild(doc.CreateElement("due"));
            invoice.AppendChild(doc.CreateElement("created"));

            XmlElement customer = doc.CreateElement("customer");


            customer.AppendChild(doc.CreateElement("firm"));
            //customer["firm"].InnerText = txtOdberatel.Text;

            customer.AppendChild(doc.CreateElement("street"));
            //customer["street"].InnerText = txtOUlice.Text;

            customer.AppendChild(doc.CreateElement("city"));
            //customer["city"].InnerText = txtOMesto.Text;

            customer.AppendChild(doc.CreateElement("zip"));
            //customer["zip"].InnerText = txtOPsc.Text;

            customer.AppendChild(doc.CreateElement("ic"));
            //customer["ic"].InnerText = txtOIc.Text;

            customer.AppendChild(doc.CreateElement("dic"));
            //customer["dic"].InnerText = txtODic.Text;



            XmlElement supplier = doc.CreateElement("supplier");

            supplier.AppendChild(doc.CreateElement("firm"));
            //supplier["firm"].InnerText = txtDodavatel.Text;

            supplier.AppendChild(doc.CreateElement("street"));
            //supplier["street"].InnerText = txtDUlice.Text;

            supplier.AppendChild(doc.CreateElement("city"));
            //supplier["city"].InnerText = txtDMesto.Text;

            supplier.AppendChild(doc.CreateElement("zip"));
            //supplier["zip"].InnerText = txtDPsc.Text;

            supplier.AppendChild(doc.CreateElement("ic"));
            //supplier["ic"].InnerText = txtDIc.Text;

            supplier.AppendChild(doc.CreateElement("dic"));
            //supplier["dic"].InnerText = txtDDic.Text;
 
            invoice.AppendChild(customer);
            invoice.AppendChild(supplier);
            invoice.AppendChild(doc.CreateElement("items"));


        }

        public void FillWithXElement(XElement xElem)
        {
            numNumber.Value = Decimal.Parse(xElem.Attribute("number").Value);
            numNumber.Enabled = false;
            dateVystaveno.Value = DateTime.Parse(xElem.Element("created").Value);
            dateSplatnost.Value = DateTime.Parse(xElem.Element("due").Value);

            txtDodavatel.Text = xElem.Element("supplier").Element("firm").Value;
            txtDUlice.Text = xElem.Element("supplier").Element("street").Value;
            txtDMesto.Text = xElem.Element("supplier").Element("city").Value;
            txtDPsc.Text = xElem.Element("supplier").Element("zip").Value;
            txtDIc.Text = xElem.Element("supplier").Element("ic").Value;
            txtDDic.Text = xElem.Element("supplier").Element("dic").Value;

            txtOdberatel.Text = xElem.Element("customer").Element("firm").Value;
            txtOUlice.Text = xElem.Element("customer").Element("street").Value;
            txtOMesto.Text = xElem.Element("customer").Element("city").Value;
            txtOPsc.Text = xElem.Element("customer").Element("zip").Value;
            txtOIc.Text = xElem.Element("customer").Element("ic").Value;
            txtODic.Text = xElem.Element("customer").Element("dic").Value;

            foreach (XElement tempElem in xElem.Element("items").Descendants("item"))
            {
                Panel panel = this.addItem();
                int iterator = 0;
                foreach (Control p in panel.Controls)
                {
                    switch (iterator)
                    {
                        case 0:
                            String ex = tempElem.Element("description").Value;
                            ((TextBox)p).Text = tempElem.Element("description").Value;
                            break;
                       case 2:
                            //String type = typeof(p).ToString();
                            ((NumericUpDown)p).Value = Decimal.Parse(tempElem.Element("count").Value);
                            break;
                        case 3:
                            ((TextBox)p).Text = tempElem.Element("price").Value;
                            break;
                        case 4:
                            ((NumericUpDown)p).Value = Decimal.Parse(tempElem.Element("vat").Value);
                            break;
                                                                                  
                    }
                    iterator++;
                }
            }
        }


    }
}
